
import { globalUtils } from '../common/js/global-utils/global-utils-all';
import { uiUtils } from '../common/js/ui-utils/ui-utils-all';
import Pure from 'pure-frontend';
import { CurrentRunningApp } from '../common/js/current-running-app';

/* SOURCE-CODE-START */

"use strict";


Pure.app.viewScope('menu-management', function (scope) {

  scope.loadTreeMenuStructure = loadTreeMenuStructure;
  scope.refreshTreeMenuStructure = refreshTreeMenuStructure;

  var _view;
  var _templateData;
  var _jqTree;

  /**
   * 加载树形菜单结构
   * @param {*} view
   * @param {*} templateData 
   */
  function loadTreeMenuStructure(view, templateData) {
    _view = view;
    _templateData = templateData;
    _jqTree = view.$ui('menuTree');

    loadMenuTreeData(function (treeData) {
      setMenuTreeData(treeData);
    });
  }

  /**
   * 刷新树形菜单结构
   */
  function refreshTreeMenuStructure() {
    var jqTree = _jqTree;
    var view = _view;

    loadMenuTreeData(function (treeData) {
      uiUtils.tree.empty(jqTree);

      var dataModel = view.getDataModel();
      dataModel.setData('childMenuData', []);

      setMenuTreeData(treeData);
    });
  }

  function loadMenuTreeData(successFn) {
    var view = _view;
    var templateData = _templateData;
    var templateId = templateData.id;
    var templateName = templateData.templateName;

    view.callService('api/menu/menu/listHierarchyMenus', {
      id: templateId
    }).waitResult(function (result) {
      if (result.success) {
        var menuData = result.data;
        // 转换成树形数据
        var treeData = CurrentRunningApp.sharing.menu.convertToTreeData(menuData);
        var templateNodeId = 'template_' + templateId;

        treeData = [{
          id: templateNodeId,
          text: templateName,
          icon: false,
          state: {
            selected: true,
            opened: true
          },
          children: treeData,
          nodeInfo: {
            type: 'template',
            data: templateData,
            childMenus: menuData
          }
        }];

        successFn(treeData);
      } else {
        Pure.app.showError(result.message);
      }
    });
  }

  function setMenuTreeData(treeData) {
    // 渲染树形控件
    uiUtils.tree.init(_jqTree, {
      'core': {
        'themes': {
          'icons': true
        },
        'data': treeData
      }
    });
  }

});

/* SOURCE-CODE-END */


